import { reactive, ref } from 'vue'
import { ArticeApi } from '../api'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { TagManageApi } from '@/view/tag-manage/api'
export class ArticleItemClass {
	private router = useRouter()
	private route = useRoute()
	ruleFormRef = ref(null)
	ruleForm = ref({
		title: '',
		content: '',
		img: '',
		type: '',
		tag: [],
		abstract: ''
	})
	rules = reactive({
		title: [{ required: true, message: '请输入标题' }],
		content: [{ required: true, message: '请输入内容' }],
		img: [{ required: true, message: '请输入封面' }],
		type: [{ required: true, message: '请选择分类' }],
		tag: [{ required: true, message: '请选择标签' }],
		abstract: [{ required: true, message: '请输入摘要' }]
	})
	public typeList = ref()
	public tagList = ref()

	constructor(ruleFormRef) {
		this.getTag()
		this.getType()
		this.ruleFormRef = ruleFormRef
		if (!this.route.query.id) {
			return
		}
		this.getDetails()
	}
	/**
	 *  提交
	 */
	public submitForm() {
		this.ruleFormRef.value.validate(valid => {
			if (!valid) return
			const params = {
				...this.ruleForm.value,
				tag: this.ruleForm.value.tag.join()
			}
			if (this.route.query.id) {
				ArticeApi.updata(params).subscribe(() => {
					ElMessage.success('编辑成功')
					this.router.push({ name: 'ArticleList' })
				})
				return
			}
			ArticeApi.createArticle(params).subscribe(() => {
				ElMessage.success('新增成功')
				this.router.push({ name: 'ArticleList' })
			})
		})
	}

	/**
	 * cancel
	 */
	public cancel() {
		this.router.push({ name: 'ArticleList' })
	}
	/**
	 * 获取文章详情
	 */
	public getDetails = () => {
		const params = {
			id: this.route.query.id
		}
		ArticeApi.queryArticleDetails(params).subscribe((res: any) => {
			this.ruleForm.value = { ...res, tag: res.tag.split(',') }
		})
	}
	public handleAvatarSuccess = res => {
		this.ruleForm.value.img = res.data.filename
	}

	/**
	 * 获取分类
	 */
	public getType() {
		ArticeApi.getType().subscribe(res => {
			this.typeList.value = res
		})
	}

	/**
	 * 获取标签
	 */
	public getTag() {
		TagManageApi.getAll().subscribe(res => {
			this.tagList.value = res
		})
	}
}
